<!-- src/views/system/user/CarMarkers.vue -->
<template>
    <div />
</template>

<script>
export default {
    name: "CarMarkers",
    props: {
        map: {
            type: Object,
            required: true,
        },
        carList: {
            type: Object,
            default: () => ({}),
        },
        carWindow: {
            type: Object,
            required: true,
        },
        carWindowContent: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            carMarkers: {}, // 存储所有车辆标记 { trainNo: marker }
            carPolylines: {}, // 存储所有轨迹线 { trainNo: polyline }
            carCurrentIndex: {}, // 存储每个车辆的当前索引 { trainNo: index }
            carPassedPath: {}, // 存储每个车辆的已走路径 { trainNo: path }
            carTimers: {}, // 存储每个车辆的定时器 { trainNo: timer }
            carRoutes: {}, // 存储每个车辆的完整路径 { trainNo: routeArray }
            moveSpeed: 30, // 移动速度（毫秒）
            colorMap: {
                "G1001": "#007BFF",
                "G0801": "#ffc107",
                "default": "#66bb6a",
            },
        };
    },
    watch: {
        carList: {
            handler(newVal) {
                console.log("CarMarkers 收到车辆列表:", newVal);
                this.updateCarList(newVal);
            },
            deep: true,
        },
        carWindowContent: {
            handler(newVal) {
                // 当显示的车辆信息窗口变化时，更新信息窗口位置
                this.updateActiveCarWindow(newVal);
            },
        },
    },
    mounted() {
        this.initCarMarkers();
    },
    beforeDestroy() {
        this.clearAllCars();
    },
    methods: {
        // 初始化所有车辆标记
        initCarMarkers() {
            if (!this.carList || Object.keys(this.carList).length === 0) {
                return;
            }

            Object.entries(this.carList).forEach(([trainNo, routeData]) => {
                if (routeData && routeData.length > 0) {
                    this.initSingleCar(trainNo, routeData);
                }
            });
        },

        // 更新车辆列表
        updateCarList(newCarList) {
            const newTrainNos = Object.keys(newCarList);
            const oldTrainNos = Object.keys(this.carMarkers);

            // 删除不存在的车辆
            oldTrainNos.forEach(trainNo => {
                if (!newTrainNos.includes(trainNo)) {
                    this.clearCar(trainNo);
                }
            });

            // 添加或更新车辆
            Object.entries(newCarList).forEach(([trainNo, routeData]) => {
                if (routeData && routeData.length > 0) {
                    if (!this.carMarkers[trainNo]) {
                        // 新车辆，初始化
                        this.initSingleCar(trainNo, routeData);
                    } else {
                        // 已存在车辆，更新路径
                        this.updateCarRoute(trainNo, routeData);
                    }
                }
            });
        },

        // 初始化单个车辆
        initSingleCar(trainNo, routeData) {
            if (!routeData || routeData.length === 0) {
                return;
            }

            console.log("初始化车辆:", trainNo, "路径点数:", routeData.length);

            // 存储路径
            this.$set(this.carRoutes, trainNo, routeData);
            this.$set(this.carCurrentIndex, trainNo, 0);
            this.$set(this.carPassedPath, trainNo, [[routeData[0].longitude, routeData[0].latitude]]);

            // 获取颜色
            const color = this.colorMap[trainNo] || this.colorMap.default;

            // 创建车辆标记
            const carMarker = new AMap.Marker({
                map: this.map,
                position: [routeData[0].longitude, routeData[0].latitude],
                icon: new AMap.Icon({
                    size: new AMap.Size(36, 36),
                    image: require("@/assets/images/car-icon.png"),
                    imageSize: new AMap.Size(36, 36),
                }),
                offset: new AMap.Pixel(-18, -18),
                angle: 0,
                autoRotation: false,
            });

            // 创建轨迹线
            const polyline = new AMap.Polyline({
                map: this.map,
                path: this.carPassedPath[trainNo],
                strokeColor: color,
                strokeOpacity: 0.8,
                strokeWeight: 6,
                strokeStyle: "solid",
                isOutline: true,
                outlineColor: "#ffffff",
                borderWeight: 1,
            });

            // 存储引用
            this.$set(this.carMarkers, trainNo, carMarker);
            this.$set(this.carPolylines, trainNo, polyline);

            // 绑定点击事件
            carMarker.on("click", () => {
                this.$emit("updateCarWindow", trainNo);
                this.carWindow.open(this.map, carMarker.getPosition());
                setTimeout(() => {
                    this.updateCarInfoWindow(trainNo);
                }, 30);
            });

            // 绑定移动事件
            carMarker.on("moving", () => {
                if (this.carWindowContent === trainNo) {
                    this.carWindow.setPosition(carMarker.getPosition());
                }
            });

            // 如果是当前显示的车辆，打开信息窗口
            if (this.carWindowContent === trainNo) {
                this.updateCarInfoWindow(trainNo);
                this.carWindow.open(this.map, carMarker.getPosition());
            }

            // 开始移动动画
            this.startCarMoving(trainNo);
        },

        // 更新车辆路径
        updateCarRoute(trainNo, routeData) {
            const currentRoute = this.carRoutes[trainNo];
            if (!currentRoute) {
                return;
            }

            if (!routeData || routeData.length === 0) {
                this.resetCarWithRoute(trainNo, routeData);
                return;
            }

            // 如果路径长度增加，说明有新数据
            if (routeData.length > currentRoute.length) {
                console.log("车辆路径更新:", trainNo, "从", currentRoute.length, "到", routeData.length);

                // 只追加新增的路径点，而不是替换整个数组
                const newPoints = routeData.slice(currentRoute.length);
                const updatedRoute = [...currentRoute, ...newPoints];
                this.$set(this.carRoutes, trainNo, updatedRoute);

                // 如果当前索引已经到达旧路径的末尾，并且没有定时器在运行，则继续移动
                if (this.carCurrentIndex[trainNo] >= currentRoute.length - 1) {
                    if (!this.carTimers[trainNo]) {
                        console.log("车辆已到达旧路径末尾，继续移动:", trainNo);
                        this.startCarMoving(trainNo);
                    }
                }
                return;
            }

            // 路径长度减少时，需要重置车辆以避免残留实时轨迹
            if (routeData.length < currentRoute.length) {
                console.log("车辆路径重置:", trainNo, "从", currentRoute.length, "回退到", routeData.length);
                this.resetCarWithRoute(trainNo, routeData);
            }
        },

        resetCarWithRoute(trainNo, routeData) {
            this.clearCar(trainNo);
            if (routeData && routeData.length > 0) {
                this.initSingleCar(trainNo, routeData);
            }
        },

        // 开始车辆移动
        startCarMoving(trainNo) {
            // 清除已有定时器
            if (this.carTimers[trainNo]) {
                clearInterval(this.carTimers[trainNo]);
            }

            const timer = setInterval(() => {
                const isFinished = this.moveCarToNextPoint(trainNo);
                if (isFinished) {
                    clearInterval(timer);
                    this.$delete(this.carTimers, trainNo);
                }
            }, this.moveSpeed);

            this.$set(this.carTimers, trainNo, timer);
        },

        // 移动车辆到下一个点
        moveCarToNextPoint(trainNo) {
            const routeData = this.carRoutes[trainNo];
            if (!routeData || routeData.length === 0) {
                return true;
            }

            const currentIndex = this.carCurrentIndex[trainNo];
            const nextIndex = currentIndex + 1;

            // 如果到达终点
            if (nextIndex >= routeData.length) {
                // 触发绘制完成事件
                this.$emit("drawComplete", trainNo);
                return true;
            }

            // 更新索引
            this.$set(this.carCurrentIndex, trainNo, nextIndex);

            const currentPoint = routeData[nextIndex];
            const position = [currentPoint.longitude, currentPoint.latitude];

            // 计算车辆朝向角度
            let angle = 0;
            if (currentIndex < routeData.length - 1) {
                const prevPoint = routeData[currentIndex];
                const nextPoint = routeData[nextIndex];
                angle = this.calculateAngle(prevPoint.longitude, prevPoint.latitude, nextPoint.longitude, nextPoint.latitude);
            }

            // 更新车辆标记位置和角度
            const carMarker = this.carMarkers[trainNo];
            if (carMarker) {
                carMarker.setPosition(position);
                carMarker.setAngle(angle);
            }

            // 更新已行驶轨迹
            this.carPassedPath[trainNo].push(position);
            const polyline = this.carPolylines[trainNo];
            if (polyline) {
                polyline.setPath(this.carPassedPath[trainNo]);
            }

            // 更新信息窗口
            if (this.carWindowContent === trainNo) {
                this.updateCarInfoWindow(trainNo);
                this.carWindow.setPosition(position);
            }

            return false;
        },

        // 计算两点之间的角度
        calculateAngle(prevLng, prevLat, nextLng, nextLat) {
            const dx = nextLng - prevLng;
            const dy = nextLat - prevLat;
            let angle = (Math.atan2(dy, dx) * 180) / Math.PI;
            angle = 90 - angle;
            if (angle < 0) angle += 360;
            if (angle >= 360) angle -= 360;
            return angle;
        },

        // 更新车辆信息窗口
        updateCarInfoWindow(trainNo) {
            const routeData = this.carRoutes[trainNo];
            const currentIndex = this.carCurrentIndex[trainNo];

            if (!routeData || currentIndex >= routeData.length || currentIndex < 0) {
                return;
            }

            const currentPoint = routeData[currentIndex];
            if (!currentPoint) {
                return;
            }

            const content = `
        <div class="tech-car-info-container">
          <div class="tech-car-info-header">
            <div class="header-icon">
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none">
                <path d="M5 12H19" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                <path d="M12 5L19 12L12 19" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
              </svg>
            </div>
            <div class="header-text">${currentPoint.trainNo || "未知车辆"}(${currentPoint.workNo || "暂无任务"})</div>
          </div>
          <div class="tech-car-info-body">
            <div class="info-grid">
              <div class="info-item">
                <div class="info-label">
                  <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" stroke="#4fc3f7" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
                  </svg>
                  线路
                </div>
                <div class="info-value">${currentPoint.lineName || "8号线"}</div>
              </div>

             
            </div>
          </div>
        </div>
      `;

            this.carWindow.setContent(content);
        },

        // 更新当前激活的车辆信息窗口
        updateActiveCarWindow(trainNo) {
            if (!trainNo || !this.carMarkers[trainNo]) {
                return;
            }

            this.updateCarInfoWindow(trainNo);
            const carMarker = this.carMarkers[trainNo];
            if (carMarker) {
                this.carWindow.open(this.map, carMarker.getPosition());
            }
        },

        // 清除单个车辆
        clearCar(trainNo) {
            // 清除定时器
            if (this.carTimers[trainNo]) {
                clearInterval(this.carTimers[trainNo]);
                this.$delete(this.carTimers, trainNo);
            }

            // 清除标记
            if (this.carMarkers[trainNo]) {
                this.carMarkers[trainNo].setMap(null);
                this.$delete(this.carMarkers, trainNo);
            }

            // 清除轨迹线
            if (this.carPolylines[trainNo]) {
                this.carPolylines[trainNo].setMap(null);
                this.$delete(this.carPolylines, trainNo);
            }

            // 清除数据
            this.$delete(this.carRoutes, trainNo);
            this.$delete(this.carCurrentIndex, trainNo);
            this.$delete(this.carPassedPath, trainNo);
        },

        // 清除所有车辆
        clearAllCars() {
            Object.keys(this.carMarkers).forEach(trainNo => {
                this.clearCar(trainNo);
            });
        },
    },
};
</script>

<style>
/* 科技感车辆信息弹窗样式 */
.tech-car-info-container {
    background: linear-gradient(145deg, #0c1e3e, #1a3a6a);
    border-radius: 12px;
    box-shadow: 0 15px 35px rgba(0, 0, 0, 0.5), 0 0 25px rgba(33, 150, 243, 0.4), inset 0 0 20px rgba(33, 150, 243, 0.3);
    border: 1px solid rgba(79, 195, 247, 0.6);
    overflow: hidden;
    min-width: 320px;
    transform-style: preserve-3d;
    position: relative;
}

.tech-car-info-container::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent, #4fc3f7, transparent);
}

.tech-car-info-header {
    background: linear-gradient(90deg, #0277bd, #0288d1);
    color: white;
    padding: 5px 16px;
    font-size: 18px;
    font-weight: 600;
    display: flex;
    align-items: center;
    gap: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
    position: relative;
    overflow: hidden;
}

.tech-car-info-header::after {
    content: "";
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: 0.5s;
}

.tech-car-info-header:hover::after {
    left: 100%;
}

.header-icon {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    padding: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid rgba(255, 255, 255, 0.3);
}

.header-text {
    letter-spacing: 1px;
    text-shadow: 0 0 8px rgba(255, 255, 255, 0.5);
}

.tech-car-info-body {
    padding: 2px 2px 0 2px;
}

.info-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 5px;
    margin-top: 5px;
}

.info-item {
    background: linear-gradient(145deg, rgba(2, 119, 189, 0.2), rgba(2, 136, 209, 0.1));
    border-radius: 10px;
    padding: 9px;
    border: 1px solid rgba(79, 195, 247, 0.3);
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.25);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.info-item::before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 2px;
    background: linear-gradient(90deg, transparent, #4fc3f7, transparent);
}

.info-item:hover {
    transform: translateY(-4px) scale(1.02);
    box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4), 0 0 20px rgba(33, 150, 243, 0.5);
    border-color: rgba(79, 195, 247, 0.7);
}

.info-label {
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 600;
    color: #4fc3f7;
    font-size: 13px;
    margin-bottom: 10px;
}

.info-value {
    color: #e3f2fd;
    font-size: 17px;
    font-weight: 700;
    text-shadow: 0 0 10px rgba(79, 195, 247, 0.6);
}

.speed-value {
    color: #4fc3f7;
    font-size: 20px;
}

.unit {
    font-size: 13px;
    color: #bbdefb;
}
</style>
